#include "Declaration.h"
#include "CSprite.h"

CSprite::CSprite(LPDIRECT3DDEVICE9 dev,char *filename,int x, int y, int width, int height, int lastframe, int animdelay)
{
	//load texture with "pink" as the transparent color
	image = new CTexture(dev);
	image->Load(filename, D3DCOLOR_XRGB(255,0,255));

	createSprite(dev);

	this->x=x;
	this->y=y;
	this->width=width;
	this->height=height;
	this->curframe=0;
	this->lastframe=lastframe;
	this->animcount=0;
	this->animdelay=animdelay;
	
}

CSprite::~CSprite()
{
	delete image;
	sprite_handler->Release();
}

int CSprite::createSprite(LPDIRECT3DDEVICE9 dev)
{
	//create sprite handler object
    HRESULT result = D3DXCreateSprite(dev, &sprite_handler);
    if (result != D3D_OK)
       return 0;
	return 1;
}

void CSprite::move(int movex, int movey)
{
	//move the sprite
    x += movex;
    y += movey;
}

void CSprite::checkOutScreen()
{
	//"warp" the sprite at screen edges
    if (x > SCREEN_WIDTH - width)
        x = 0;
    if (x < 0)
        x = SCREEN_WIDTH - width;
}

void CSprite::animate()
{
	//has animation delay reached threshold?
        if (++animcount > animdelay)
        {
            //reset counter
            animcount = 0;

            //animate the sprite
            if (++curframe > lastframe)
			{
                curframe = 0;
					
			}
        }
}

void CSprite::draw()
{
	//start sprite handler
	sprite_handler->Begin(D3DXSPRITE_ALPHABLEND);

	//create vector to update sprite position
	D3DXVECTOR3 position((float)x, (float)y, 0);

	//configure the rect for the source tile
    RECT srcRect;
    int columns = 8;
    srcRect.left = (curframe % columns) * width;
    srcRect.top = (curframe / columns) * height;
    srcRect.right = srcRect.left + width;
	srcRect.bottom = srcRect.top + height;

	//draw the sprite
    sprite_handler->Draw(
        image->GetTexture(), 
        &srcRect,
        NULL,
        &position,
        D3DCOLOR_XRGB(255,255,255));

	//stop drawing
    sprite_handler->End();
}

bool CSprite::collide(CSprite *sprite2)
{
	RECT rect1;
    rect1.left = x+1;
    rect1.top = y+1;
    rect1.right = x + width-1;
    rect1.bottom = y + height-1;

    RECT rect2;
	rect2.left = sprite2->getX()+1;
	rect2.top = sprite2->getY()+1;
	rect2.right = sprite2->getX() + sprite2->getWidth()-1;
	rect2.bottom = sprite2->getY() + sprite2->getHeight()-1;

    RECT dest;
    return IntersectRect(&dest, &rect1, &rect2);
}